package com.emergency.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.emergency.data.entity.*;
import com.emergency.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * 导入物资数据
 */
@Slf4j
@RestController
@RequestMapping("/export")
public class DataController {

    //=========================专家库excel导入 START=================================

    @Resource
    private DutiesMapper dutiesMapper;
    @Resource
    private IndustryMapper industryMapper;
    @Resource
    private ExpertGroupMapper expertGroupMapper;

    private static final String name = "姓名";
    private static final String duties = "职称";
    private static final String industry = "从事行业及特长";
    private static final String work = "工作单位";
    private static final String phone = "联系方式";

    @PostMapping("/expertGroup")
    public String export(MultipartFile file) {
        try {
            //文件输入流
            InputStream stream = file.getInputStream();
            //读取excel表格对象
            ExcelReader reader = ExcelUtil.getReader(stream);
            //读取数据
            List<Map<String, Object>> rows = reader.readAll();
            for (Map<String, Object> row : rows) {
                ExpertGroup expertGroup = new ExpertGroup();
                expertGroup.setName(MapUtil.getStr(row, name));
                expertGroup.setCompany(MapUtil.getStr(row, work));
                expertGroup.setPhone(MapUtil.getStr(row, phone));
                //职称
                String dutiesName = MapUtil.getStr(row, duties);
                Duties duties = dutiesMapper.selectOne(new QueryWrapper<Duties>()
                        .eq("duties_name", dutiesName)
                        .last("LIMIT 1"));
                if (duties != null) {
                    expertGroup.setDutiesId(duties.getId());
                }
                //从事行业和特长
                String industryName  = MapUtil.getStr(row, industry);
                Industry industry = industryMapper.selectOne(new QueryWrapper<Industry>()
                        .eq("industry_name", industryName)
                        .last("LIMIT 1"));
                if (industry != null) {
                    expertGroup.setIndustryId(industry.getId());
                }
                expertGroupMapper.insert(expertGroup);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "导入数据成功";
    }

    //=========================专家库excel导入 END=================================

    //=========================联系点excel导入 START=================================

    @Resource
    private LinkmanPointMapper linkmanPointMapper;
    @Resource
    private LinkmanPointContactMapper linkmanPointContactMapper;
    @Resource
    private StreetMapper streetMapper;
    @Resource
    private VillageMapper villageMapper;

    private static final String streetName = "乡镇街道名称";
    private static final String emergencyType = "应急类型";
//    private static final String responsiblePerson = "负责人";
    private static final String responsiblePersonLinkWay = "联络方式";
    private static final String linkman = "联络人";
    private static final String linkmanLinkWay = "联系方式";
    private static final String secretary = "村书记";
    private static final String villageHead = "村长（主任）";
    private static final String villageCommittee = "村委员";
    private static final String villageLinkWay = "村委联系方式";
    private static final String villageName = "村（社区）名称";

    /**
     * 联系点excel导入
     *
     * @param file excel
     * @param type 类型 0-乡镇/街道 1-村/社区
     * @return String
     */
    @PostMapping("/linkmanPoint")
    public String linkmanPoint(MultipartFile file, Integer type) {
        try {
            //文件输入流
            InputStream stream = file.getInputStream();
            //读取excel表格对象
            ExcelReader reader = ExcelUtil.getReader(stream);
            //读取数据
            List<Map<String, Object>> rows = reader.readAll();
            //乡镇/街道
            if (type == 0) {
                for (Map<String, Object> row : rows) {
                    //查询有无联系点记录
                    // 查询街道名称
                    Street street = streetMapper.selectOne(new QueryWrapper<Street>()
                            .eq("street_name", MapUtil.getStr(row, streetName))
                            .last("LIMIT 1"));
                    if (street == null) {
                        log.info("Excel中的 {} 在数据库中无对应数据", MapUtil.getStr(row, streetName));
                    } else {
                        LinkmanPoint point = linkmanPointMapper.selectOne(new QueryWrapper<LinkmanPoint>()
                                .eq("street_id", street.getId())
                                .last("LIMIT 1"));
                        //联系点id
                        Long pointId;
                        if (point == null) {
                            LinkmanPoint linkmanPoint = new LinkmanPoint();
                            linkmanPoint.setStreetId(street.getId());
                            linkmanPoint.setType(0);
                            linkmanPointMapper.insertAndReturnId(linkmanPoint);
                            pointId = linkmanPoint.getId();
                        } else {
                            pointId = point.getId();
                        }
                        //联络人
                        String person = MapUtil.getStr(row, linkman);
                        if (StrUtil.isNotBlank(person)) {
                            LinkmanPointContact contact = new LinkmanPointContact();
                            contact.setLinkman(person);
                            contact.setPhone(MapUtil.getStr(row, linkmanLinkWay));
                            contact.setEmergencyType(MapUtil.getStr(row, emergencyType));
                            contact.setLinkmanPointId(pointId);
                            contact.setType(0);
                            linkmanPointContactMapper.insert(contact);
                        }
                    }
                }
            }
            //村/社区
            if (type == 1) {
                for (Map<String, Object> row : rows) {
                    //查询有无联系点记录
                    // 查询街道名称
                    Street street = streetMapper.selectOne(new QueryWrapper<Street>()
                            .eq("street_name", MapUtil.getStr(row, streetName))
                            .last("LIMIT 1"));
                    // 查询村社区名称
                    Village village = villageMapper.selectOne(new QueryWrapper<Village>()
                            .eq("village_name", MapUtil.getStr(row, villageName))
                            .last("LIMIT 1"));
                    if (village == null) {
                        log.info("Excel中的 {} 在数据库中无对应数据", MapUtil.getStr(row, villageName));
                    } else {
                        LinkmanPoint point = linkmanPointMapper.selectOne(new QueryWrapper<LinkmanPoint>()
                                .eq("street_id", street.getId())
                                .eq("village_id", village.getId())
                                .last("LIMIT 1"));
                        //联系点id
                        Long pointId;
                        if (point == null) {
                            LinkmanPoint linkmanPoint = new LinkmanPoint();
                            linkmanPoint.setStreetId(street.getId());
                            linkmanPoint.setType(1);
                            linkmanPoint.setVillageId(village.getId());
                            linkmanPointMapper.insertAndReturnId(linkmanPoint);
                            pointId = linkmanPoint.getId();
                        } else {
                            pointId = point.getId();
                        }
                        //村书记
                        String secretaryValue = MapUtil.getStr(row, secretary);
                        if (StrUtil.isNotBlank(secretaryValue)) {
                            LinkmanPointContact contact = new LinkmanPointContact();
                            contact.setLinkman(secretaryValue);
                            contact.setPhone(MapUtil.getStr(row, responsiblePersonLinkWay));
                            contact.setLinkmanPointId(pointId);
                            contact.setType(1);
                            contact.setDuties(secretary);
                            linkmanPointContactMapper.insert(contact);
                        }
                        //村长
                        String villageHeadValue = MapUtil.getStr(row, villageHead);
                        if (StrUtil.isNotBlank(villageHeadValue)) {
                            LinkmanPointContact contact = new LinkmanPointContact();
                            contact.setLinkman(villageHeadValue);
                            contact.setPhone(MapUtil.getStr(row, linkmanLinkWay));
                            contact.setLinkmanPointId(pointId);
                            contact.setType(1);
                            contact.setDuties(villageHead);
                            linkmanPointContactMapper.insert(contact);
                        }
                        //村委
                        String villageCommitteeValue = MapUtil.getStr(row, villageCommittee);
                        if (StrUtil.isNotBlank(villageCommitteeValue)) {
                            LinkmanPointContact contact = new LinkmanPointContact();
                            contact.setLinkman(villageCommitteeValue);
                            contact.setPhone(MapUtil.getStr(row, villageLinkWay));
                            contact.setLinkmanPointId(pointId);
                            contact.setType(1);
                            contact.setDuties(villageCommittee);
                            linkmanPointContactMapper.insert(contact);
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "导入数据成功";
    }

    //=========================联系点excel导入 END=================================

    //=========================应急资源excel导入 END=================================

    @Resource
    private EmergencySuppliesPointMapper emergencySuppliesPointMapper;
    @Resource
    private EmergencyPointSuppliesMapper emergencyPointSuppliesMapper;

    private static final String STREET = "街道";
    private static final String VILLAGE = "村社区";
    private static final String SUPPLIES = "物资名称";
    private static final String SPECIFICATION = "规格";
    private static final String NUMBER = "数量";
    private static final String UNIT = "单位";
    private static final String ADDRESS = "地点";
    private static final String USE = "用途";
    private static final String LINKMAN = "联系人";
    private static final String WAY = "联系方式";

    @PostMapping("/resource")
    public String resource(MultipartFile file) {
        try {
            //文件输入流
            InputStream stream = file.getInputStream();
            //读取excel表格对象
            ExcelReader reader = ExcelUtil.getReader(stream);
            //读取数据
            List<Map<String, Object>> rows = reader.readAll();
            //遍历
            for (Map<String, Object> row : rows) {
                //街道
                String streetName = StrUtil.trim(MapUtil.getStr(row, STREET));
                Street street = streetMapper.selectOne(new QueryWrapper<Street>()
                        .eq("street_name", streetName)
                        .last("LIMIT 1"));
                //村社区
                String villageName = StrUtil.trim(MapUtil.getStr(row, VILLAGE));
                Village village = villageMapper.selectOne(new QueryWrapper<Village>()
                        .eq("village_name", villageName)
                        .last("LIMIT 1"));
                //物资名称
                String suppliesName = StrUtil.trim(MapUtil.getStr(row, SUPPLIES));
                //规格
                String specification = MapUtil.getStr(row, SPECIFICATION);
                //数量
                Integer number = MapUtil.getInt(row, NUMBER);
                if (number == null) {
                    number = 0;
                }
                //单位
                String unit = StrUtil.trim(MapUtil.getStr(row, UNIT));
                //地点
                String address = StrUtil.trim(MapUtil.getStr(row, ADDRESS));
                //地点为空的数据跳过
                if (StrUtil.isBlank(address)) {
                    continue;
                }
                //用途
                String use = StrUtil.trim(MapUtil.getStr(row, USE));
                //联系人
                String linkman = StrUtil.trim(MapUtil.getStr(row, LINKMAN));
                //联系方式
                String way = StrUtil.trim(MapUtil.getStr(row, WAY));
                //查询条件
                QueryWrapper<EmergencySuppliesPoint> query = new QueryWrapper<>();
                if (street != null) {
                    query.eq("street_id", street.getId());
                }
                if (village != null) {
                    query.eq("village_id", village.getId());
                }
                query.eq("storage_location", address);
                //应急资源点ID
                Long id;
                //查询是否存在应急资源点
                EmergencySuppliesPoint point = emergencySuppliesPointMapper.selectOne(query.last("LIMIT 1"));
                if (point == null) {
                    EmergencySuppliesPoint newPoint = new EmergencySuppliesPoint();
                    newPoint.setPointName(address);
                    newPoint.setStorageLocation(address);
                    if (street != null) {
                        newPoint.setStreetId(street.getId());
                    }
                    if (village != null) {
                        newPoint.setVillageId(village.getId());
                    }
                    newPoint.setLinkman(linkman);
                    newPoint.setPhone(way);
                    emergencySuppliesPointMapper.insertAndReturnId(newPoint);
                    id = newPoint.getId();
                } else {
                    id = point.getId();
                }
                //查询物资是否重复
                EmergencyPointSupplies supplies = emergencyPointSuppliesMapper.selectOne(new QueryWrapper<EmergencyPointSupplies>()
                        .eq("emergency_supplies_point_id", id)
                        .eq("supplies_name", suppliesName)
                        .last("LIMIT 1"));
                if (supplies == null) {
                    EmergencyPointSupplies newSupplies = new EmergencyPointSupplies();
                    newSupplies.setSuppliesName(suppliesName);
                    newSupplies.setSpecification(specification);
                    newSupplies.setQuantity(number);
                    newSupplies.setUnit(unit);
                    newSupplies.setUtility(use);
                    newSupplies.setEmergencySuppliesPointId(id);
                    emergencyPointSuppliesMapper.insert(newSupplies);
                }
                log.info("街道 {} 村社区 {} 地点 {} 的应急资源点和应急物资导入成功", streetName, villageName, address);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "导入数据成功";
    }

    //=========================应急资源excel导入 END=================================

    //=========================安置点excel导入 END=================================

    @Resource
    private SettlementPointMapper settlementPointMapper;

    private static final String SITE = "场所名称";
    private static final String X = "经度";
    private static final String Y = "纬度";

    @PostMapping("/settlement")
    public String settlement(MultipartFile file) {
        try {
            //文件输入流
            InputStream stream = file.getInputStream();
            //读取excel表格对象
            ExcelReader reader = ExcelUtil.getReader(stream);
            //读取数据
            List<Map<String, Object>> rows = reader.readAll();
            for (Map<String, Object> row : rows) {
                //场所名称
                String siteName = StrUtil.trim(MapUtil.getStr(row, SITE));
                //地址
                String address = StrUtil.subBefore(siteName, "避", false);
                //经度
                String x = MapUtil.getStr(row, X);
                //纬度
                String y = MapUtil.getStr(row, Y);
                //联系人
                String linkman = StrUtil.trim(MapUtil.getStr(row, LINKMAN));
                //联系方式
                String way = StrUtil.trim(MapUtil.getStr(row, WAY));
                //街道
                String streetName = StrUtil.trim(MapUtil.getStr(row, STREET));
                Street street = streetMapper.selectOne(new QueryWrapper<Street>()
                        .eq("street_name", streetName)
                        .last("LIMIT 1"));
                //村社区
                String villageName = StrUtil.trim(MapUtil.getStr(row, VILLAGE));
                Village village = villageMapper.selectOne(new QueryWrapper<Village>()
                        .eq("village_name", villageName)
                        .last("LIMIT 1"));
                SettlementPoint point = settlementPointMapper.selectOne(new QueryWrapper<SettlementPoint>()
                        .eq("site_name", siteName)
                        .last("LIMIT 1"));
                if (point == null) {
                    SettlementPoint newPoint = new SettlementPoint();
                    newPoint.setSiteName(siteName);
                    newPoint.setAddress(address);
                    newPoint.setX(x);
                    newPoint.setY(y);
                    newPoint.setLinkman(linkman);
                    newPoint.setPhone(way);
                    if (street != null) {
                        newPoint.setStreetId(street.getId());
                    }
                    if (village != null) {
                        newPoint.setVillageId(village.getId());
                    }
                    settlementPointMapper.insert(newPoint);
                    log.info("避灾安置点---- {} ----导入数据成功", siteName);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "导入数据成功";
    }

    @Resource
    private SettlementPointSuppliesMapper settlementPointSuppliesMapper;

    @PostMapping("/settlementPointSupplies")
    public String x(MultipartFile file) {
        try {
            //文件输入流
            InputStream stream = file.getInputStream();
            //读取excel表格对象
            ExcelReader reader = ExcelUtil.getReader(stream);
            //读取数据
            List<Map<String, Object>> rows = reader.readAll();
            //遍历
            for (Map<String, Object> row : rows) {
                //物资名称
                String suppliesName = StrUtil.trim(MapUtil.getStr(row, SUPPLIES));
                //规格
                String specification = MapUtil.getStr(row, SPECIFICATION);
                //数量
                Integer number = MapUtil.getInt(row, NUMBER);
                if (number == null) {
                    number = 0;
                }
                //单位
                String unit = StrUtil.trim(MapUtil.getStr(row, UNIT));
                //地点
                String address = StrUtil.trim(MapUtil.getStr(row, ADDRESS));
                //地点为空的数据跳过
                if (StrUtil.isBlank(address)) {
                    continue;
                }
                //用途
                String use = StrUtil.trim(MapUtil.getStr(row, USE));
                //查询物资点
                SettlementPoint point = settlementPointMapper.selectOne(new QueryWrapper<SettlementPoint>()
                        .eq("site_name", "德清县钟管镇" + address));
                if (point == null) {
                    log.info("{} 地点的对应安置点为空", address);
                    continue;
                }
                //查询物资是否重复
                SettlementPointSupplies supplies = settlementPointSuppliesMapper.selectOne(new QueryWrapper<SettlementPointSupplies>()
                        .eq("settlement_point_id", point.getId())
                        .eq("supplies_name", suppliesName)
                        .last("LIMIT 1"));
                if (supplies == null) {
                    SettlementPointSupplies newSupplies = new SettlementPointSupplies();
                    newSupplies.setSuppliesName(suppliesName);
                    newSupplies.setQuantity(number);
                    newSupplies.setUtility(use);
                    newSupplies.setUnit(unit);
                    newSupplies.setSpecification(specification);
                    newSupplies.setSettlementPointId(point.getId());
                    settlementPointSuppliesMapper.insert(newSupplies);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "导入数据成功";
    }

    //=========================安置点excel导入 END=================================

    @Resource
    private DepartmentMapper departmentMapper;

    private static String BUMEN = "所属部门";

    @PostMapping("/tongxunlu")
    public String tongxunlu(MultipartFile file) {
        try {
            //文件输入流
            InputStream stream = file.getInputStream();
            //读取excel表格对象
            ExcelReader reader = ExcelUtil.getReader(stream);
            //读取数据
            List<Map<String, Object>> rows = reader.readAll();
            for (Map<String, Object> row : rows) {
                String bu = MapUtil.getStr(row, BUMEN);
                if (StrUtil.isNotBlank(bu)) {
                    bu = bu.trim();
                    Department selectOne = departmentMapper.selectOne(new QueryWrapper<Department>()
                            .eq("dept_name", bu));
                    if (selectOne == null) {
                        Department department = new Department();
                        department.setDeptName(bu);
                        department.setType(1);
                        departmentMapper.insert(department);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "SUCCESS";
    }

    private static String REN = "联系人";
    private static String HUA = "联系电话";
    private static String QU = "所属区划";

    @Resource
    private AddressBookMapper addressBookMapper;

    @PostMapping("/xun")
    public String xun(MultipartFile file) {
        try {
            //文件输入流
            InputStream stream = file.getInputStream();
            //读取excel表格对象
            ExcelReader reader = ExcelUtil.getReader(stream);
            //读取数据
            List<Map<String, Object>> rows = reader.readAll();
            for (Map<String, Object> row : rows) {
                AddressBook book = new AddressBook();
                String ren = MapUtil.getStr(row, REN);
                String hua = MapUtil.getStr(row, HUA);
                String qu = MapUtil.getStr(row, QU);
                String bu = MapUtil.getStr(row, BUMEN);
                if (StrUtil.isNotBlank(bu)) {
                    bu = bu.trim();
                    Department selectOne = departmentMapper.selectOne(new QueryWrapper<Department>()
                            .eq("dept_name", bu));
                    if (selectOne != null) {
                        book.setDeptId(selectOne.getId());
                    }
                }
                if (StrUtil.isNotBlank(qu)) {
                    qu = qu.trim();
                    Street street = streetMapper.selectOne(new QueryWrapper<Street>()
                            .eq("street_name", qu));
                    if (street != null) {
                        book.setStreetId(street.getId());
                    }
                }
                book.setName(ren);
                book.setPhone(hua);
                addressBookMapper.insert(book);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "SUCCESS";
    }
}
